﻿/// <reference path="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" />    
function MapLocation(panel) {
    this.UI = new Object();
    this.UI.Panel = $(panel);
    this.UI.InputLatitude = this.UI.Panel.find('input[data-type=latitude]');
    this.UI.InputLongitude = this.UI.Panel.find('input[data-type=longitude]');

    var p = $('<div style="padding: 20px 20px 10px;"><label for="' + this.UI.Panel.attr('id') + '_input">Szukaj lokalizacji: </label><input type="text" style="margin-top:3px;" id="' + this.UI.Panel.attr('id') + '_input" /><span class="description">Możesz również dwuktotnie kliknąć na mapie i wskazać punkt, jak i chwycić i przesunąć już istniejący marker.</span></div>');
    this.UI.UserInput = p.find('input');
    this.UI.Panel.append(p);
    this.UI.Map = $('<div style="margin:0 20px;height:400px;" />');
    this.UI.Map.attr('id', this.UI.Panel.attr('id') + '_map');
    this.UI.Panel.append(this.UI.Map);

    this.Location = this.GetInitialLocation();
    var mapCenter = this.Location;
    if (!mapCenter)
        mapCenter = this.GetStoredLocation();
    if (!mapCenter)
        mapCenter = new google.maps.LatLng(51.801687, 19.398968);

    var zoom = parseInt($.cookie('stored-map-location-zoom'));
    if (!zoom)
        zoom = 14;

    var mapOptions = {
        zoom: zoom,
        center: mapCenter,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.Map = new google.maps.Map(this.UI.Map[0], mapOptions);

    var mapLocation = this;

    google.maps.event.addListener(this.Map, 'zoom_changed', function () {
        $.cookie('stored-map-location-zoom', mapLocation.Map.getZoom(), { expires: 31 });
    });

    this.Marker = null;
    if (this.Location)
        this.SetMarker(this.Location);

    this.GeoCoder = new google.maps.Geocoder();

    var wto = 0;
    this.UI.UserInput.keypress(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            if (wto > 0)
                window.clearTimeout(wto);
            wto = window.setTimeout(function () {
                wto = 0;
                mapLocation.Find();
            }, 50);
        }
    });
    google.maps.event.addListener(this.Map, 'dblclick', function (e) {
        mapLocation.SetMarker(e.latLng, true);
    });
};
MapLocation.prototype.Find = function () {
    var mapLocation = this;
    var address = this.UI.UserInput.val();
    this.GeoCoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            mapLocation.Map.setCenter(results[0].geometry.location);
            mapLocation.SetMarker(results[0].geometry.location, true);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
};

MapLocation.prototype.SetMarker = function (latLng, insertValuesForPostback) {
    $.cookie('stored-map-location', latLng.lat().toString() + ';' + latLng.lng().toString(), { expires: 31 });
    var addListener = true;
    if (this.Marker)
        addListener = false;
    this.Location = latLng;
    if (!this.Marker) {
        this.Marker = new google.maps.Marker({
            position: latLng,
            map: this.Map,
            draggable: true,
            animation: google.maps.Animation.DROP
        });
    } else
        this.Marker.position = latLng;
    if (addListener) {
        var mapLocation = this;
        google.maps.event.addListener(this.Marker, 'dragend', function () {
            var latLng = mapLocation.Marker.getPosition();
            mapLocation.UI.InputLatitude.val(latLng.lat().toString());
            mapLocation.UI.InputLongitude.val(latLng.lng().toString());
            mapLocation.Location = latLng;
        });
    }
    if (insertValuesForPostback) {
        this.UI.InputLatitude.val(latLng.lat().toString());
        this.UI.InputLongitude.val(latLng.lng().toString());
    }
};

MapLocation.prototype.GetInitialLocation = function () {
    var lat, lng;
    lat = parseFloat(this.UI.InputLatitude.val().replace(',', '.'));
    lng = parseFloat(this.UI.InputLongitude.val().replace(',', '.'));
    if (lat && lng)
        return new google.maps.LatLng(lat, lng);
    else
        return null;
}

MapLocation.prototype.GetStoredLocation = function () {
    if ($.cookie('stored-map-location')) {
        var latLng = $.cookie('stored-map-location');
        latLng = latLng.split(';');
        if (latLng.length != 2) return null;
        var lat, lng;
        lat = parseFloat(latLng[0]);
        lng = parseFloat(latLng[1]);
        if (lat && lng)
            return new google.maps.LatLng(lat, lng);
    } else {
        return null;
    }
};

$(function () {
    $('div[data-panel=map-wrapper]').each(function () {
        $(this).data('map-location', new MapLocation($(this)));
    });
    $('.record-display[tab-id]').each(function () {
        var $tab = $(this);
        if ($tab.find('div[data-panel=map-wrapper]').length > 0) {
            $tab.bind('tabshow', function () {
                $('div[data-panel=map-wrapper]').each(function () {
                    var map = $(this).data('map-location').Map;
                    var c = map.getCenter();
                    google.maps.event.trigger(map, 'resize');
                    map.setCenter(c);
                });
            });
        }
    });
});